﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sinacor.Infra.Service.Security.Authentication.ServiceCredentials;
using System.Configuration;
using PSE.Framework.ProviderLoader.Configuration;
using PSE.Framework.Configuration;
using PSE.Framework.ProviderLoader;

namespace Sinacor.Infra.Service.Security.Authentication.ServiceCredentials
{
    /// <summary>
    /// Classe para captura e criação da Instância do Provider de Autenticação do Token
    /// </summary>
    public class SecurityTokenAutenticationProviderFactory
    {
        private const string providerKey = "SecurityTokenAuthenticationProvider";
        private const string CONFIG_SECTION_NAME = "serviceProviders";

        /// <summary>
        /// Retorna o provider de Autenticação
        /// </summary>
        /// <returns>Instância do provider de autenticação configurado.</returns>
        public static ISecurityTokenAuthenticationProvider RetrieveProvider()
        {
            try
            {
                ProviderConfigurationSection configSection = ApplicationConfiguration.GetCurrent().GetSection<ProviderConfigurationSection>(CONFIG_SECTION_NAME);

                if (ProviderLoader<ISecurityTokenAuthenticationProvider>.ProviderExists(configSection.Providers, providerKey))
                {
                    return ProviderLoader<ISecurityTokenAuthenticationProvider>.LoadProvider(configSection.Providers, providerKey);
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                //System.Diagnostics.EventLog.WriteEntry("SecurityTokenAutenticationProviderFactory", ex.Message,System.Diagnostics.EventLogEntryType.Error);
                throw new ConfigurationErrorsException("Could not create an instance of Authentication Provider configured.", ex);
            }
        }
    }
}
